import time
import random


from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.views import APIView

from cart.cartser import CartSerializer
from cart.models import CartModel
from order.models import UserCoupon, OrderModel, OrderDetailModel, MyCourseModel
from order.orderser import UserCouponSerializer, OrderSerializer, OrderDetailSerializer, MyCourseSerializer
from user.models import UserModel
from utils.authorization import MyAuthentication
from utils.myredis import redistoll
from django.db import transaction

# Create your views here.


class CartView(ListAPIView):
    queryset = CartModel.objects.all()
    serializer_class = CartSerializer
    authentication_classes = [MyAuthentication, ]
    def get_queryset(self):
        user=self.request.query_params.get("user")
        if user:
            return self.queryset.filter(user=user,select=True)


class CouponView(APIView):
    authentication_classes = [MyAuthentication, ]
    def get(self,request):
        user=request.query_params.get("user")
        userinfo=UserModel.objects.get(id=user)
        mycoupon=UserCoupon.objects.filter(user=user)
        ser = UserCouponSerializer(instance=mycoupon,many=True)
        return Response({"code":200,"msg":"请求参数","data":{"credit":userinfo.credit,"tomoney":10,"coupon":ser.data}})

def get_order_number():
    order_number = "XY"+str(time.strftime('%Y%m%d%H%M%S')) + str(random.randint(1000,9999))
    return order_number

class Order(APIView):
    authentication_classes = [MyAuthentication, ]
    def post(self,request):
        user=request.data.get('user')
        order=redistoll.getstr(user)
        if order:
            return Response({"code":200,"msg":'请勿重复提交订单'})
        transac=transaction.savepoint()
        try:
            orderdata={
                "orderno":get_order_number(),
                "user":user,
                "score":request.data.get('score',0),
                "coupon":request.data.get('coupon',None),
                "paytype":request.data.get('paytype',1),
            }
            cart=CartModel.objects.filter(user=user,select=True)
            total=0
            for item in cart:
                total+=item.course.discount
            orderdata["totalprice"]=total
            orderdata["payprice"]=total
            if orderdata['score']!=0:
                orderdata['payprice']=float(orderdata['totalprice'])-orderdata['score']/10
            if orderdata['coupon']!=None:
                cou=UserCoupon.objects.filter(id=orderdata['coupon']).first()
                if cou.isshow:
                    orderdata['payprice']=orderdata['totalprice']-cou.coupon.price
            orderser=OrderSerializer(data=orderdata)
            if orderser.is_valid():
                orderser.save()
                redistoll.setstrno(user,orderdata['orderno'])
                for item in cart:
                    detail={
                        "order":orderser.data.get("id"),
                        "course":item.course.id,
                        "cname":item.course.cname,
                        "price":item.course.price,
                        "discount":item.course.discount,
                        "cover":"http://127.0.0.1:8000/uploads/"+str(item.course.cover),
                    }
                    detailser=OrderDetailSerializer(data=detail)
                    if detailser.is_valid():
                        detailser.save()
                    else:
                        return Response(detailser.errors)
                    item.delete()
            else:
                return Response(orderser.errors)
            redistoll.delkey(user)
            transaction.savepoint_commit(transac)
            return Response({"msg":"订单生成成功","id":orderser.data.get("id"),"timeout":30})
        except:
            transaction.savepoint_rollback(transac)
            return Response({"msg":"订单生成失败"})


from utils.Alipay import AliPaySDK
class AliPayLink(APIView):
    authentication_classes = [MyAuthentication,]
    def get(self,request):
        oid=request.query_params.get('order')
        order=OrderModel.objects.filter(id=oid).first()
        if order:
            ali=AliPaySDK()
            return Response(ali.page_pay(order.orderno,order.payprice,"向浮光付款"))
        else:
            return Response({"msg":"订单不存在"})


class AlipayResult(APIView):
    def get(self,request):
        ali=AliPaySDK()
        data=request.query_params.dict()
        result=ali.check_sign(data)
        if result:
            order=OrderModel.objects.filter(orderno=data.get("out_trade_no")).first()
            order.status=1
            order.payno=data.get('trade_no')
            order.paytime=data.get('timestamp')
            order.save()
            if order.score:
                user=UserModel.objects.filter(id=order.user.id).first()
                user.credit=user.credit-order.score
                user.save()
            if order.coupon:
                coupon=UserModel.objects.filter(id=order.coupon).first()
                coupon.isshow=False
                coupon.save()
            course=OrderDetailModel.objects.filter(order=order.id)
            ser=OrderDetailSerializer(course,many=True)
            for item in course:
                mydata={
                    "user":order.user.id,
                    "course":item.course.id,
                    "cname":item.course.cname,
                    "price":item.course.price,
                    "discount":item.course.discount,
                    "cover":str(item.course.cover)
                }
                myser=MyCourseSerializer(data=mydata)
                if myser.is_valid():
                    myser.save()
                else:
                    return Response({"msg":myser.errors})
            return Response({"msg":"支付成功","course":ser.data,"paytime":order.paytime,"payprice":order.payprice})
        else:
            return Response({"msg":"支付失败"})

class MyCourseView(APIView):
    def get(self,request):
        user=request.query_params.get("user")
        info=MyCourseModel.objects.filter(user=user)
        ser=MyCourseSerializer(instance=info,many=True)
        return Response(ser.data)


class OrderPagination(PageNumberPagination):
    page_size = 2
    page_size_query_param = 'size'
    page_query_param = 'page'

class MyOrderView(ListAPIView):
    authentication_classes = [MyAuthentication, ]
    queryset = OrderModel.objects.all()
    serializer_class = OrderSerializer
    pagination_class = OrderPagination
    def get_queryset(self):
        status=self.request.query_params.get('status')
        user=self.request.query_params.get("user")
        print(user,status)
        if status=="-1":
            return self.queryset.filter(user=user)
        else:
            return self.queryset.filter(user=user,status=status)

class StatusView(APIView):
    def get(self,request):
        return Response([{'id': 0, 'name': '未支付'},{'id': 1, 'name': '已支付'},{'id': 2, 'name': '已完成'}])


